package MyTimer;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long tmie;
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.tmie=System.currentTimeMillis()+delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.tmie-o.tmie);
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTmie() {
        return tmie;
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker=new Object();
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            queue.offer(new MyTimerTask(runnable,delay));
            locker.notify();
        }
    }

    public MyTimer(){
        Thread t=new Thread(()->{
            while(true){
                try{
                    synchronized (locker){
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task=queue.peek();
                        long curTime=System.currentTimeMillis();

                        if(curTime>= task.getTmie()){
                            task.getRunnable().run();
                            queue.poll();
                        }else{
                            locker.wait(task.getTmie()-curTime);
                        }
                    }
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class Timer {
    public static void main(String [] args){
        MyTimer timer=new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        System.out.println("程序开始执行");
    }
}
